/*
  Copyright 2011 Jonathan Albarrán León

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.jaal.movilconsultanet;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

public class Util {

	private static Context context;

	private static final String REGEXP_PARENT = ".+?\\d+(,\\d+)?.*?[^(rows)].*?((/(\\d){2}){2}|--)";
	private static final Pattern REGEXP_CHILD = Pattern.compile("-?(\\d+\\.)?\\d+(,\\d+)?",Pattern.DOTALL);
	private static final Pattern REGEXP_UNIT = Pattern.compile("[^/(<td|\\s?class|\"datosGeneral\"|>)]\\w+",Pattern.DOTALL);
	private static final Pattern REGEXP_DATE = Pattern.compile("((\\d){2}/){2}(\\d){2}",Pattern.DOTALL);
	public static String UNKNOWN_ERROR = "";
	public static final String UNKNOWN_DATE = "--";
	
	public static Context getContext() {
		return context;
	}

	public static void setContext(Context context) {
		Util.context = context;
		
		UNKNOWN_ERROR = context.getResources().getString(R.string.unknown_error);
	}

	public static boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		boolean online = false;
		if (netInfo != null) {
			online = netInfo.isConnected();
		}
		if (!online) {
			Toast.makeText(context,
					R.string.no_connection,
					Toast.LENGTH_SHORT).show();
			Log.d("isOnline", "No connection active");
		}
		
		return online;
	}

	public static String createURLParameters(Map<String, String> parametros)
			throws UnsupportedEncodingException {

		StringBuilder urlParamString = new StringBuilder();

		for (String param : parametros.keySet()) {
			urlParamString.append(param + "="
					+ URLEncoder.encode(parametros.get(param)) + "&");
		}
		return urlParamString.toString();

	}

	public static Map<String, String> getRegExp(String row, StringBuilder response) {

		Map<String, String> result = new HashMap<String, String>();
		
		Pattern p = Pattern.compile(row+REGEXP_PARENT, Pattern.DOTALL);
		Matcher m = p.matcher(response);
		if (m.find()) {

			String matched = m.group();
			Matcher innerM = REGEXP_CHILD.matcher(matched);
			
			//busco Balance Disponible y Total
			

			result.put("disponible", innerM.find() ? innerM.group() : UNKNOWN_ERROR);
			
			int end = -1;
			
			if (innerM.find()) {

				result.put("total", innerM.group());

				//esto para empezar la siguiente busqueda desde el indice en que quedo la ultima busqueda
				end = innerM.end();
			} else {
				result.put("total", UNKNOWN_ERROR);
			}
			
			//Busco la Unidad
			innerM = REGEXP_UNIT.matcher(matched);
			
			//notese que uso la variable entera "end" para buscar desde el ultimo indice
			result.put("unidad", innerM.find(end) ? innerM.group() : UNKNOWN_ERROR);
			
			//Busco la Fecha
			innerM = REGEXP_DATE.matcher(matched);
			result.put("fecha", innerM.find(end) ? innerM.group() : UNKNOWN_DATE);
			
			
		} else {
			result.put("total", UNKNOWN_ERROR);
			result.put("disponible", UNKNOWN_ERROR);
			result.put("unidad", UNKNOWN_ERROR);
			result.put("fecha", UNKNOWN_DATE);
		}
		return result;
	}
	
	
	public static String getRegExp(StringBuilder response, StringBuilder parentRegExp,
			StringBuilder childRegExp) {

		Pattern p = Pattern.compile(parentRegExp.toString(), Pattern.DOTALL);
		Matcher m = p.matcher(response);
		if (m.find()) {
			String matched = m.group();
			Pattern innerP = Pattern.compile(childRegExp.toString(),
					Pattern.DOTALL);
			Matcher innerM = innerP.matcher(matched);
			if (innerM.find()) {
				return innerM.group();
			} else {
				return matched;
			}
		}
		return UNKNOWN_ERROR;
	}
	
	public static String getGSMSessionParameter(String url){
		
		Pattern p = Pattern.compile("id=\\w+$", Pattern.DOTALL);
		Matcher m = p.matcher(url);
		if (m.find()) {
			String matched = m.group();
				return matched;
		}
		return null;
	}
	
	public static String getCodTlf(String num) {
		if (num.equals("0426")) {
			return "199";
		}
		if (num.equals("0416")) {
			return "158";
		}
		return null;
	}
	
	public static String getCodTlfMovilnet(String num) {
		if (num.equals("158")) {
			return "0416";
		}
		if (num.equals("199")) {
			return "0426";
		}
			return null;
	}
}
